import * as React from "react";
import {AppBreadcrumbs} from "../../common/AppBreadcrumbs";
import Tab from "@material-ui/core/Tab";
import TabContext from "@material-ui/lab/TabContext";
import TabList from "@material-ui/lab/TabList";
import {BaseProps} from "../../../App";

interface AppDetailState {
    tabs: {
        data: Array<{ id: string; name: string; path: string }>;
        currentId: string;
    }
}

export class AppDetail extends React.Component<BaseProps, AppDetailState> {
    breadcrumbs = [{
        name: '首页', path: '/home'
    }, {
        name: '应用管理', path: '/app'
    }, {
        name: '应用详情', path: '/detail'
    }];

    constructor(props: BaseProps) {
        super(props);
        this.tabChanged = this.tabChanged.bind(this);
        const data = [{id: '1', name: '构建', path: 'build'}, {id: '2', name: '发布', path: 'deploy'}];
        this.state = {
            tabs: {
                data: data,
                currentId: '1'
            }
        };
    }

    tabChanged(event: any, value: any) {
        this.setState({
            tabs: {...this.state.tabs, currentId: value}
        });
        const item = this.state.tabs.data.filter(item => item.id === value)[0];
        let appId = this.props.match.params.appId;
        this.props.history.push('/app/' + appId + '/' + item.path);
    }

    componentDidMount(): void {
        const currentTab = this.buildCurrentTabId(this.props.location.pathname, this.state.tabs.data);
        console.log(currentTab)
        this.setState({
            tabs: {...this.state.tabs, currentId: currentTab}
        });
    }

    render() {
        return <div className={'main-content'}>
            <AppBreadcrumbs breadcrumbs={this.breadcrumbs} onClick={(path: any) => this.props.history.push(path)}/>
            <TabContext value={this.state.tabs.currentId}>
                <TabList indicatorColor="primary" textColor="primary" onChange={this.tabChanged} centered>
                    {this.state.tabs.data.map((item, index) => (<Tab key={index} value={item.id} label={item.name}/>))}
                </TabList>
            </TabContext>
        </div>;
    }

    buildCurrentTabId(pathname: any, data: any) {
        let paths = pathname.split('/');
        for (let i = 0; i < paths.length; i++) {
            for (let j = 0; j < data.length; j++) {
                if (paths[i] === data[j].path) {
                    return data[j].id;
                }
            }
        }
        return data[0].id;
    }
}
